﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Management;

namespace Cashier.utils
{
    public class ToolsUtil
    {
        /// <summary>
        /// 获取总页数
        /// </summary>
        /// <param name="record"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public static long GetPagecount(long record, int pagesize)
        {
            long pagecount = 1;
            if (record > 0 && pagesize > 0)
            {
                if (record % pagesize > 0)
                    pagecount = record / pagesize + 1;
                else
                    pagecount = record / pagesize;
            }
            return pagecount;
        }

        /// <summary>
        /// 格式化货币数据
        /// </summary>
        /// <param name="money"></param>
        /// <returns></returns>
        public static String FormatMoneyNumber(Decimal money)
        {
            String formatString = String.Empty;
            try
            {
                NumberFormatInfo formatInfo = new NumberFormatInfo();
                formatInfo.CurrencyDecimalDigits = 2;

                formatString = money.ToString("N", formatInfo);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return formatString;
        }

        /// <summary>
        /// 生成出货单号
        /// </summary>
        /// <returns></returns>
        public static String GenerateShipmentNO()
        {
            String shipmentno = String.Empty;
            shipmentno = DateTime.Now.ToString("yyMMddHHmmssfff") + (int)(new Random().NextDouble() * 100000);
            return shipmentno;
        }

        /// <summary>
        /// 生成退货单号
        /// </summary>
        /// <returns></returns>
        public static String GenerateReshipmentNO()
        {
            String reshipmentno = String.Empty;
            reshipmentno = DateTime.Now.ToString("yyMMddHHmmssfff") + (int)(new Random().NextDouble() * 100000);
            return reshipmentno;
        }

        /// <summary>
        /// 生成采购进货单号
        /// </summary>
        /// <returns></returns>
        public static String GeneratePurchaseNO()
        {
            String reshipmentno = String.Empty;
            reshipmentno = DateTime.Now.ToString("yyMMddHHmmssfff") + (int)(new Random().NextDouble() * 100000);
            return reshipmentno;
        }

        /// <summary>
        /// 生成采购退货单号
        /// </summary>
        /// <returns></returns>
        public static String GenerateRepurchaseNO()
        {
            String reshipmentno = String.Empty;
            reshipmentno = DateTime.Now.ToString("yyMMddHHmmssfff") + (int)(new Random().NextDouble() * 100000);
            return reshipmentno;
        }

        /// <summary>
        /// 获取当前月的总天数
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public static int GetDaysOfMonth(int year, int month)
        {
            int days = 0;
            switch (month)
            {
                case 1: days = 31;
                    break;
                case 2:
                    if (year % 4 > 0)
                        days = 28;
                    else
                        days = 29;
                    break;
                case 3: days = 31;
                    break;
                case 4: days = 30;
                    break;
                case 5: days = 31;
                    break;
                case 6: days = 30;
                    break;
                case 7: days = 31;
                    break;
                case 8: days = 31;
                    break;
                case 9: days = 30;
                    break;
                case 10: days = 31;
                    break;
                case 11: days = 30;
                    break;
                case 12: days = 31;
                    break;
            }
            return days;
        }

        /// <summary>
        /// 判断是否连接internet
        /// </summary>
        /// <returns></returns> 
        public static bool IsConnInternet()
        {
            bool isConnInternet = false;
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                webResponse.Close();
                isConnInternet = true;
            }
            catch
            { }
            return isConnInternet;
        }

        /// <summary>
        /// 积分兑换金额
        /// </summary>
        /// <param name="integral"></param>
        /// <returns></returns>
        public static Decimal IntegralExchangeMoney(int integral)
        {
            Decimal money = 0M;
            if (integral > 0 && Config.EXCHANGEMONEY > 0)
            {
                int m = integral / Config.EXCHANGEMONEY;
                if (m > 0)
                {
                    money = m;
                }
            }
            return money;
        }

        /// <summary>
        /// 金额兑换积分
        /// </summary>
        /// <param name="money"></param>
        /// <returns></returns>
        public static int MoneyExchangeIntegral(Decimal money)
        {
            int integral = 0;
            if (money > 0)
            {
                int m = (Int32)money;
                if (m > 0 && Config.SPENDEXCHANGE>0)
                {
                    integral = m / Config.SPENDEXCHANGE;
                }
            }
            return integral;
        }

        /// <summary>
        /// 检测程序是否有新版本
        /// </summary>
        /// <returns></returns>
        public static int CheckNewVersion()
        {
            int versionCount = 0;
            if (IsConnInternet())
            {
                String localPath = System.Windows.Forms.Application.StartupPath;
                String url = "http://www.daysmei.com/client/upgrade.jsp?method=versioninfo&clientType=single";
                try
                {
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                    Stream stream = webResponse.GetResponseStream();
                    StreamReader sr = new StreamReader(stream, System.Text.Encoding.GetEncoding("utf-8"));
                    String info = sr.ReadToEnd();
                    
                    if (!String.IsNullOrEmpty(info))
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(info);
                        XmlElement root = doc.DocumentElement;
                        XmlNodeList nodeList = root.ChildNodes;
                        foreach(XmlNode lopNode in nodeList)
                        {
                            XmlNodeList childNodeList = lopNode.ChildNodes;
                            String name = String.Empty;
                            String path = String.Empty;
                            String version = String.Empty;
                            long size = 0L;
                            String type = String.Empty;
                            int versionCode = 0;
                            foreach (XmlNode lopChildNode in childNodeList)
                            {
                                String nodeName = lopChildNode.Name;
                                if (nodeName.Equals("name"))
                                {
                                    name = lopChildNode.InnerText;
                                }
                                else if (nodeName.Equals("path"))
                                {
                                    path = lopChildNode.InnerText;
                                }
                                else if (nodeName.Equals("version"))
                                {
                                    version = lopChildNode.InnerText;
                                }
                                else if (nodeName.Equals("size"))
                                {
                                    size = long.Parse(lopChildNode.InnerText.Trim());
                                }
                                else if (nodeName.Equals("type"))
                                {
                                    type = lopChildNode.InnerText;
                                }
                                else if (nodeName.Equals("versionCode"))
                                {
                                    versionCode = Int32.Parse(lopChildNode.InnerText.Trim());
                                }
                            }

                            if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(path) && !String.IsNullOrEmpty(version))
                            {
                                int versionInt = 0;
                                int localVersionInt = 0;
                                FileInfo fileInfo = new FileInfo(localPath + @"\" + name);
                                if (fileInfo.Exists && (type.Equals("exe") || type.Equals("dll")))
                                {
                                    versionInt = Int32.Parse(version.Replace(".", ""));
                                    String localVersion = GetProgramVersion(localPath, name);
                                    localVersionInt = Int32.Parse(localVersion.Replace(".", ""));
                                }
                                if (type.Equals("txt") || type.Equals("sql"))
                                {
                                    versionInt = Int32.Parse(version.Replace(".", ""));
                                    doc.Load(localPath + @"\config.xml");
                                    root = doc.DocumentElement;
                                    String versionNode = "version";
                                    if (type.Equals("sql"))
                                    {
                                        versionNode = "sqlversion";
                                    }
                                    String localVersion = String.Empty;
                                    XmlNode xmlNode = root.SelectSingleNode("/config/setting/" + versionNode);
                                    if (xmlNode != null)
                                    {
                                        localVersion = xmlNode.InnerText;
                                    }
                                    if (String.IsNullOrEmpty(localVersion))
                                    {
                                        localVersion = "1.0.0.0";
                                    }
                                    localVersionInt = Int32.Parse(localVersion.Replace(".", ""));
                                }
                                if (versionInt > localVersionInt)
                                {
                                    versionCount++;
                                }
                                fileInfo = null;
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            return versionCount;
        }

        /// <summary>
        /// 获取程序集版本号
        /// </summary>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static String GetProgramVersion(String localPath, String programName)
        {
            String version = String.Empty;
            String programPath = localPath + @"\" + programName;
            FileInfo fileInfo = new FileInfo(programPath);
            if (fileInfo.Exists)
            {
                System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(programPath);
                version = info.FileVersion;
            }
            return version;
        }

        /// <summary>
        /// 获取主程序版本
        /// </summary>
        /// <returns></returns>
        public static String GetMainProgramVersion()
        {
            String version = String.Empty;
            String programPath = System.Windows.Forms.Application.ExecutablePath;
            FileInfo fileInfo = new FileInfo(programPath);
            if (fileInfo.Exists)
            {
                System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(programPath);
                version = info.FileVersion;
            }
            return version;
        }

        /// <summary>
        /// 获取本机IP地址
        /// </summary>
        /// <returns></returns>
        public static String GetLocalIP()
        {
            String localIP = String.Empty;
            try
            {
                if (IsConnInternet())
                {
                    String hostName = Dns.GetHostName();
                    IPHostEntry ipe = Dns.GetHostEntry(hostName);
                    if (ipe != null)
                    {
                        if (ipe.AddressList != null && ipe.AddressList.Length > 0)
                        {
                            int i = 1;
                            StringBuilder sb = new StringBuilder();
                            foreach (IPAddress ipa in ipe.AddressList)
                            {
                                sb.Append(hostName).Append("[").Append(i).Append("]:").Append(ipa.ToString()).Append(" ");
                                i++;
                            }
                            localIP = sb.ToString();
                        }
                    }
                }
            }
            catch
            { }
            return localIP;
        }

        /// <summary>
        /// 判断打印机是否准备好打印
        /// </summary>
        /// <param name="printName"></param>
        /// <returns></returns>
        public static bool IsReadyWithPrinter(String printName)
        {
            bool isReady = false;
            try
            {
                string path = @"win32_printer.DeviceId='" + printName + "'";
                ManagementObject printer = new ManagementObject(path);
                printer.Get();
                Console.WriteLine(printer["WorkOffline"].ToString());
                Object obj = printer.Properties["PrinterStatus"].Value;
                if (obj != null)
                {
                    int sta = Convert.ToInt32(obj);
                    if (sta > 2 && sta < 8)
                    {
                        isReady = true;
                    }
                }
            }
            catch
            { }
            return isReady;
        }
    }
}
